package com.chasing.baseframe.common;

import android.content.Context;
import android.text.TextUtils;

import com.chasing.baseframe.MyApplication;

import net.chasing.androidbaseconfig.util.NumberUtils;
import net.chasing.androidbaseconfig.util.ToastUtils;

public class CommonFunctionManager {

    // region 网络请求失败统一处理提示
    public static final String COMMON_ERROR_TIP = "网络开小差了~请再试一次";

    // 注意：服务器有返回code的，则进行调用code，result参数的方法
    public static void requestFailedTip(String result) {
        requestFailedTip(MyApplication.INSTANCE, 0, result);
    }

    public static void requestFailedTip(int code, String result) {
        requestFailedTip(MyApplication.INSTANCE, code, result);
    }

    public static void requestFailedTip(Context context, int code, String result) {
        if (code == 100007 || code == 100035) return;
        if (context == null) return;
        ToastUtils.showShort(context, getErrorTip(code, result));
    }

    public static String getErrorTip(int code, String result) {
        if (code != 0 && !TextUtils.isEmpty(result)) {
            return result;
        } else if (TextUtils.isEmpty(result)) {
            return COMMON_ERROR_TIP;
        } else if (result.toLowerCase().contains("failed to connect to")) {
            return "当前网络连接失败，请尝试在设置中检查APP联网控制权限是否开启！";
        } else if (result.contains("connect timed out") || result.contains("timeout")) {
            return COMMON_ERROR_TIP;
        } else if (result.contains("HTTP 404")) {
            return "404错误，链接异常";
        } else if (result.contains("HTTP 500") || result.contains("HTTP 502")) {
            return "系统繁忙";
        } else if (result.contains("No such file or directory")) {
            return "未找到相应文件";
        } else if (result.contains("No address associated with hostname") || result.contains("No route to host") || result.contains("Unable to resolve host")) {
            return "请检测网络配置";
        } else {//其他未知异常
            return COMMON_ERROR_TIP;
        }
        // https的可能会报：
        // java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
    }

    // 生成长度为32的随机字符串
    public static String generateId() {
        return NumberUtils.GenerateGUID().replace("-", "");
    }
}
